<template>
    <el-button v-if="propJson.isAddData" class="addClass" type="primary" @click="add()">
        <component is="PlusOutlined" style="padding-right: 10px"/>
        添 加
    </el-button><el-button v-if="propJson.isSonTable && propJson.isAddSonTable" class="addClass" type="primary" @click="addSonTable()">
        <component is="PlusOutlined" style="padding-right: 10px"/>
        添 加 子 表 格
    </el-button>
    <el-table :data="tableData"
              :border="propJson.isBorder"
              :stripe="propJson.isStripe"
              :show-overflow-tooltip="propJson.isOverFlowTip"
              :max-height="propJson.isMaxHeight ? propJson.maxHeight : -1"
              :style="propJson.editFlag ? 'width: 98%; margin-left: 1%;' : ''"
              @selection-change="tableSelect"
              :span-method="sonTableSpanMethod"
                :info2="getDynamicColumns">
        <el-table-column prop="ywuEditorInnerId" label="序号" :width="70" align="center"></el-table-column>
        <el-table-column v-for="(item, index) in resTableFiledList"
                         :prop="item.variableField"
                         :label="item.variableLabel"
                         :align="item.isAlignCenter">
            <template #default="scope">
                <span v-if="!scope.row[propJson.sonTableTypeName] && item.isEditor">
                    <el-input v-model="scope.row[item.variableField]" :disabled="item.isDisable" v-if="item.isEditor && item.editorType === 'input'" @change="inputChange(scope.row)"/>
                    <el-switch v-model="scope.row[item.variableField]" :disabled="item.isDisable" v-if="item.isEditor && item.editorType === 'switch'" @change="inputChange(scope.row)"/>
                    <el-select v-model="scope.row[item.variableField]" :disabled="item.isDisable" v-if="item.isEditor && item.editorType === 'dropDown'" @click="selectClick(index)" @change="inputChange(scope.row)">
                        <el-option v-for="item in item.selectOptions" :key="item.value" :label="item.label" :value="item.value"/>
                    </el-select>
                </span>
                <span v-if="scope.row[propJson.sonTableTypeName] && scope.cellIndex === 1">
                    <EditTableCommon :prop-json="propJson" :common-param="commonParam" :table-data="scope.row[propJson.sonTableName]"/>
                </span>
            </template>
        </el-table-column>

        <el-table-column align="center" :width="80" v-if="propJson.isDeleteData">
            <template #header>
                <span>操 作</span>
            </template>
            <template #default="scope">
                <el-button type="default" size="small" @click="deleteData(scope.row)">
                    <component is="DeleteTwoTone"/>
                </el-button>
            </template>
        </el-table-column>
    </el-table>
</template>

<script name="EditTableCommon" setup lang="ts">
import {commonParamChange} from "@/utils/commonParamUtil";
import jsonpath from "jsonpath";
import {doThirdServiceValue} from "@/utils/lowcode/thirdService";
import {computed, defineProps, ref} from "vue";

let props = defineProps(['propJson', 'commonParam', 'tableData']);
let propJson = computed(() => {return props['propJson']})
let commonParam = computed(() => {return props['commonParam']})
let tableData = computed(() => {return props['tableData']})

let resTableFiledList = ref([])

resTableFiledList.value = propJson.value.tableFieldList;

let getDynamicColumns = computed( async() => {
    if (propJson.value.isDynamicColumns) {
        // 启用了动态列，需要获取对应动态列的数据
        await doThirdServiceValue(propJson.value.dynamicColumnsInfo, commonParam.value, execThen, () => {}, null)
    }
})

// 初始化时变量所有字段，如果为下拉选项字段则加载下拉选项值
init()
function init() {
    getSelectOptions();
    if (tableData.value) {
        for (let index = 0; index < tableData.value.length; index++) {
            let info = tableData.value[index]
            info["ywuEditorInnerId"] = index + 1;
        }
    }
}

function add() {
    // 构建待插入的对象
    let info = {}
    for (let index = 0; index < propJson.value.tableFieldList.length; index++) {
        let fieldName = propJson.value.tableFieldList[index].variableField
        if (propJson.value.tableFieldList[index].editorType === "switch") {
            info[fieldName] = false
        } else {
            info[fieldName] = ""
        }
    }
    tableData.value.push(info);
    // 为每一行数据添加一个序号
    for (let index = 0; index < tableData.value.length; index++) {
        let info = tableData.value[index]
        info["ywuEditorInnerId"] = index + 1;
    }
}

function inputChange(row) {
    // 根据序号修改数据
    let paramInfo = tableData.value
    for (let index = 0; index < paramInfo.length; index++) {
        let info = paramInfo[index]
        if (info["ywuEditorInnerId"] === row["ywuEditorInnerId"]) {
            paramInfo[index] = row
            break
        }
    }
}

function deleteData(row) {
    // 根据序号删除数据
    let deleteIndex = -1
    let paramInfo = tableData.value
    for (let index = 0; index < paramInfo.length; index++) {
        let info = paramInfo[index]
        if (info["ywuEditorInnerId"] === row["ywuEditorInnerId"]) {
            deleteIndex = index
            break
        }
    }
    paramInfo.splice(deleteIndex, 1);
}

function tableSelect(val) {
    // 获取变量名称
    let paramName = propJson.value.selectVarParamName
    commonParamChange(commonParam.value, paramName, val)
}

function selectOptionsThen(resValue, execParam) {
    // 根据返回的结果解析label和value
    let optionsList = []
    for (let i = 0; i < resValue.length; i++) {
        let op = {label: "", value: ""}
        let info = resValue[i]
        let opLabel = jsonpath.query(info, execParam.optionLabel)
        let opValue = jsonpath.query(info, execParam.optionValue)
        if (opLabel.length > 0 && opValue.length > 0) {
            op.label = opLabel[0]
            op.value = opValue[0]
            optionsList.push(op)
        }
    }
    execParam.selectOptions = optionsList
}

async function getSelectOptions() {
    for (let index = 0; index < propJson.value.tableFieldList.length; index++) {
        let fieldInfo = propJson.value.tableFieldList[index]
        if (fieldInfo.isOptionClickAction) {
            continue;
        }
        if (fieldInfo.isEditor && fieldInfo.editorType === 'dropDown') {
            if (propJson.value.editFlag) {
                return;
            }
            await doThirdServiceValue(fieldInfo.actionInfo, commonParam.value, selectOptionsThen, () => {}, fieldInfo)
        }
    }
}

function addSonTable() {
    // 构建待插入的对象
    let info = {}
    info[propJson.value.sonTableName] = [];
    info[propJson.value.sonTableTypeName] = true;
    tableData.value.push(info);
    // 为每一行数据添加一个序号
    for (let index = 0; index < tableData.value.length; index++) {
        let tempInfo = tableData.value[index]
        tempInfo["ywuEditorInnerId"] = index + 1;
    }
}

function sonTableSpanMethod(info) {
    if (info.row[propJson.value.sonTableTypeName] && info.columnIndex === 1) {
        return [1, propJson.value.tableFieldList.length];
    } else if (info.row[propJson.value.sonTableTypeName] && (info.columnIndex > 1 && info.columnIndex <= propJson.value.tableFieldList.length)) {
        return [0, 0];
    } else {
        return [1, 1];
    }
}

async function selectClick(index) {
    if (propJson.value.editFlag) {
        return;
    }
    let fieldInfo = propJson.value.tableFieldList[index]
    if (!fieldInfo.isOptionClickAction) {
        return;
    }
    await doThirdServiceValue(fieldInfo.actionInfo, commonParam.value, selectOptionsThen, () => {}, fieldInfo)
}

function execThen(resValue) {
    let tempList = [];
    for (let index = 0; index < propJson.value.tableFieldList.length; index++ ) {
        tempList.push(propJson.value.tableFieldList[index])
    }
    for (let i = 0; i < resValue.length; i++) {
        let tempItem = resValue[i];
        let item = {
            variableLabel: tempItem.columnName,
            variableField: tempItem.columnField,
            isEditor: tempItem.isEditor,
            isDisable: tempItem.isDisable,
            editorType: tempItem.editorType,
        }
        tempList.push(item);
    }
    resTableFiledList.value = tempList;
}
</script>

<style scoped lang="less">
.addClass {
    margin-bottom: 20px;
    margin-top: 10px;
    margin-right: 20px;
    float: right;
    width: 10%;
}
</style>